//
//  MainTableViewController.m
//  InTime
//
//  Created by zhangjia on 15/9/9.
//  Copyright (c) 2015年 ClownYoJoy. All rights reserved.
//

#import "MainTableViewController.h"
#import "MainNavigationController.h"
#import "GeneralHeader.h"
#import "AppSizeHeader.h"
#import "NewsListModel.h"
#import "ITNewsCell.h"
#import "ITNewsHeaderView.h"
#import "PhotosetViewController.h"

@interface MainTableViewController ()

@property (strong, nonatomic) NSMutableData *mData;//接收解析的数据
@property (strong, nonatomic) NSMutableArray *dataArray;//数据数组
@property (strong, nonatomic) NewsListModel *topNewsModel;//头条新闻
@property (strong, nonatomic) MainNavigationController *mainNaVC;


@end

@implementation MainTableViewController

static NSString * const reuseIdentifier = @"CommonNewsCell";
static NSString * const headerID = @"ITNewsHeaderView";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"InTimeNews";
    self.dataArray = [NSMutableArray array];
    [self analysisData];
    //导航条背景图片
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"test"] forBarMetrics:UIBarMetricsDefault];
    //tableview背景图片
    self.tableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"启动图.jpg"]];
    
    self.mainNaVC = (MainNavigationController *)self.navigationController;
    
    [self.tableView registerClass:[ITNewsHeaderView class] forHeaderFooterViewReuseIdentifier:headerID];

    // self.clearsSelectionOnViewWillAppear = NO;
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewsListModel *model = self.dataArray[indexPath.row];
    //确定Cell的重用类型
    NSString *ID = [ITNewsCell idForRow:model];
    ITNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    cell.model = model;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ITNewsHeaderView *headerView = [[ITNewsHeaderView alloc] initWithReuseIdentifier:headerID];
    NSLog(@"Top:%@", self.topNewsModel);
    headerView.model = self.topNewsModel;
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 200;
}

#pragma Table View Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = [ITNewsCell heightForRow:self.dataArray[indexPath.row]];
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PhotosetViewController *photosetVC = [[PhotosetViewController alloc] init];
    [self.mainNaVC pushViewController:photosetVC animated:YES];
}

#pragma mark - 网络请求 & 数据解析
- (void)analysisData {
    //首页 数据
    //http://c.m.163.com/nc/article/headline/T1348647853363/0-140.html
    //http://c.m.163.com/nc/article/list/T1370583240249/0-140.html
    NSString *urlString = @"http://c.m.163.com/nc/article/headline/T1348647853363/0-140.html";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    self.mData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.mData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSDictionary *totalDic = [NSJSONSerialization JSONObjectWithData:self.mData options:0 error:nil];
    for (NSDictionary *dic in [totalDic objectForKey:@"T1348647853363"]) {
        NewsListModel *model = [[NewsListModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        NSLog(@"%@| %@", model.skipType, model.title);
        if (model.alias) {
            self.topNewsModel = model;
        }else if (!model.skipType|| [model.skipType isEqualToString:@"photoset"])  {//
        [self.dataArray addObject:model];
        }
        [self.tableView reloadData];
    }
    NSLog(@"%ld", self.dataArray.count);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"请求失败,网络错误");
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
